package data;

import entities.User;
import exceptions.AuthException;
import exceptions.TokenAuthException;
import javax.servlet.http.HttpServletRequest;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author bertram
 */
public class Auth {

    private DataProvider prov = new DataProvider();

    public Auth() {
    }

    private void checkToken(String token) throws TokenAuthException {

        if (prov.checkToken(token)); else {
            throw new TokenAuthException("invalid token");
        }
    }

    private User login(String username, String password) throws AuthException {
        User user = prov.getUser(username, password);
        if (user == null) {
            throw new AuthException("wrong username or password");
        } else {
            return user;
        }
    }

    public synchronized User checkAuth(HttpServletRequest req) throws AuthException {
        /*ok, hvad gør vi her? vi tager imod et request
        og checker først efter et token, hvis dette ikke findes
        eller checktoken ikke returnerer true kaster vi en authexception
        denne authexception griber vi og finder et username/password i requestet.
        hvis dette ikke returnerer et token, som checktoken accepterer eskalerer vi authexception
        og lader kalderen håndtere den.*/


        String username = (String) req.getParameter("username");
        String password = (String) req.getParameter("password");
        if (req.getSession().getAttribute("user") != null) {
            return (User)req.getSession().getAttribute("user");

        } else if (username != null && password != null) {
            User user = login(username, password);
            req.getSession(true).setAttribute("user", user);
            return user;
        } else {
            throw new AuthException("not logged in");
        }
    }
}
